package handler

import (
	"day1031/cache"
	"day1031/model"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"strconv"
	"time"
)

func Like(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	var article model.Article
	model.DB.Where("id = ?", id).Limit(1).Find(&article)
	data := model.Article{
		Title:   article.Title,
		Content: article.Content,
		Picture: article.Picture,
	}
	redis_key := "article_" + strconv.Itoa(id)
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	jsonData, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Detail(c *gin.Context) {
	var data []model.Article
	redis_key := "article_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情展示成功",
		"data": data,
	})
	return
}
